package com.yesin.cart.service;

import com.yesin.cart.client.GoodsClient;
import com.yesin.cart.interceptor.LoginInterceptor;
import com.yesin.cart.pojo.Cart;
import com.yesin.geteway.exception.ExceptionEnum;
import com.yesin.geteway.exception.YsException;
import com.yesin.geteway.utils.JsonUtils;
import com.yesin.item.pojo.Sku;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.yesin.auth.entity.UserInfo;

import java.util.List;
import java.util.stream.Collectors;


@Service
public class CartService {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private GoodsClient goodsClient;

    private static final String KEY_PREFIX = "user:cart:";

    private static final Logger LOGGER = LoggerFactory.getLogger(CartService.class);

    public void addCart(Cart cart) {
        // 获取用户信息
        UserInfo userInfo = LoginInterceptor.getUserInfo();

        // 查询购物车记录
        BoundHashOperations<String, Object, Object> hashOperation = this.redisTemplate.boundHashOps(KEY_PREFIX + userInfo.getId());

        String key = cart.getSkuId().toString();
        // 临时变量num，用于更新数量
        Integer num = cart.getNum();

        // 判断当前的商品是否再购物车中
        if (hashOperation.hasKey(key)) {
            // 在，更新数量
            String cartJson = hashOperation.get(key).toString();
            // 反序列化，获取redis中的cart
            cart = JsonUtils.parse(cartJson, Cart.class);
            cart.setNum(cart.getNum() + num);
            // 序列化，将cart保存在redis中
        } else {
            // 不在，新增购物车
            Sku sku = this.goodsClient.querySkuBySkuId(cart.getSkuId());
            if (sku == null){
                LOGGER.error("微服务调用失败，未找到id:{}的SKU", cart.getSkuId());
                throw new YsException(ExceptionEnum.SKU_NOT_FOUND);
            }
            cart.setTitle(sku.getTitle());
            // 取出主图片的地址
            cart.setImage(StringUtils.isBlank(sku.getImages()) ? "" : StringUtils.split(sku.getImages(), ",")[0]);
            cart.setOwnSpec(sku.getOwnSpec());
            cart.setPrice(sku.getPrice());
            cart.setUserId(userInfo.getId());
        }
        hashOperation.put(key, JsonUtils.serialize(cart));
    }

    public List<Cart> queryCart() {
        // 获取用户信息
        UserInfo userInfo = LoginInterceptor.getUserInfo();
        // 判断用户是否有购物车记录
        if (!this.redisTemplate.hasKey(KEY_PREFIX + userInfo.getId())){
            return null;
        }
        // 查询购物车记录
        BoundHashOperations<String, Object, Object> hashOperation = this.redisTemplate.boundHashOps(KEY_PREFIX + userInfo.getId());
        List<Object> cartsJson = hashOperation.values();
        if (CollectionUtils.isEmpty(cartsJson)){
            return null;
        }
        List<Cart> carts = cartsJson.stream().map(cartJson -> JsonUtils.parse(cartJson.toString(), Cart.class)).collect(Collectors.toList());
        return carts;
    }

    public void updateNum(Cart cart) {
        // 获取用户信息
        UserInfo userInfo = LoginInterceptor.getUserInfo();
        // 查询购物车记录
        BoundHashOperations<String, Object, Object> hashOperation = this.redisTemplate.boundHashOps(KEY_PREFIX + userInfo.getId());
        // 从redis中取出数据，并解析
        String key = cart.getSkuId().toString();
        Integer num = cart.getNum();
        String cartJson = hashOperation.get(key).toString();
        cart = JsonUtils.parse(cartJson, Cart.class);
        // 将数据进行修改
        cart.setNum(num);
        // 将数据序列化再放入redis
        hashOperation.put(key, JsonUtils.serialize(cart));
    }

    public void deleteCart(String skuId) {
        // 获取用户信息
        UserInfo userInfo = LoginInterceptor.getUserInfo();
        // 查询购物车记录
        BoundHashOperations<String, Object, Object> hashOperation = this.redisTemplate.boundHashOps(KEY_PREFIX + userInfo.getId());
        Long delete = hashOperation.delete(skuId);
        if (delete != 1){
            LOGGER.error("商品删除失败，skuId:{}", skuId);
            throw new YsException(ExceptionEnum.SKU_DELETE_FAIL);
        }

    }
}
